<?php

namespace App\Http\Controllers;

use Laravel\Lumen\Routing\Controller as BaseController;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;

class Controller extends BaseController
{
    public function __construct()
    {
        $dir = storage_path();
        if (!is_dir($dir)) @mkdir($dir, 0777);
        $dir = storage_path() . "/framework";
        if (!is_dir($dir)) @mkdir($dir, 0777);
        if (!is_dir($dir . "/cache")) @mkdir($dir . "/cache", 0777);
        if (!is_dir($dir . "/views")) @mkdir($dir . "/views", 0777);
        if (!is_dir($dir . "/sessions")) @mkdir($dir . "/sessions", 0777);
        $dir = storage_path() . "/logs";
        if (!is_dir($dir)) @mkdir($dir, 0777);
        $this->apitmp = new Logger('apitmp');
        $this->apitmp->pushHandler(
            (new RotatingFileHandler(storage_path() . '/logs/apitmp.log', 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        $this->dt = (new \DateTime("now"))->format('Y-m-d H:i:s'); //Carbon::now();
    }

    public function returnMsg($code = 200, $msg = '成功', $data = [])
    {
        return [
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ];
    }

    /**
     * 过滤前端的参数，得到自己真正需要的参数  错误的话 返回错误信息
     * @param $request  Request对象
     * @param array $mustFields 必填字段
     * @param array $editFields 可选字段
     * @param array $msgField 必填字段对应返回错误信息
     * @return array
     */
    public function getRealData($request, $mustFields = array(), $optionalFields = array(), $msgField = array())
    {
        $values = array();

        $editFields = array_unique(array_merge($mustFields, $optionalFields));

        //没有字段
        if (!$editFields) {
            return '参数不能为空';
        }

        //验证必填字段
        foreach ($mustFields as $field) {
            if (!(isset($request[$field]) && $request[$field] !== '')) {
                $msg = '参数错误';
                if (!empty($msgField[$field])) {
                    $msg = $msgField[$field];
                }
                return $msg;
            }
        }

        //格式化可选字段的传参
        foreach ($editFields as $field) {
            if (isset($request[$field])) {
                $values[$field] = trim($request[$field]);
            }
        }

        return $values;
    }
}
